﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorldBankBBS.Logic;

namespace WorldBankBBS.Pathing
{
    public class PathRouter
    {
        private Session _session = null;

        private Dictionary<string, IPathHandler> _handlers = new Dictionary<string, IPathHandler>();

        public PathRouter(Session session)
        {
            _session = session;
        }

        public enum RouteResult
        {
            Success, NoSession, EmptyPath, IllegalPath, UnknownObject
        }

        public RouteResult PerformRoute(string path)
        {
            if (_session == null) return RouteResult.NoSession;
            if (string.IsNullOrWhiteSpace(path)) return RouteResult.EmptyPath;

            var parts = path.Split(new []{':'});
            
            if (parts.Length < 3) return RouteResult.IllegalPath;

            var assemblyName = parts[0];
            var objectName = parts[1];
            var action = parts[2];

            if (!_handlers.ContainsKey(objectName))
            {
                var type = Type.GetType(objectName + ", " + assemblyName);
                if(type == null) return RouteResult.UnknownObject;

                var o = Activator.CreateInstance(type, new[] {_session}) as IPathHandler;

                if(o == null) return RouteResult.UnknownObject;

                _handlers.Add(objectName, o);
            }

            var handler = _handlers[objectName];
            handler.ProcessPath(action);

            return RouteResult.Success;
        }
    }
}
